﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileWebsiteGenerator.Entities;
using MobileWebsiteGenerator.Models;
using MobileWebsiteGenerator;

namespace MobileWebsiteGenerator.Areas.Admin.Controllers
{
    public class AdminCustomerController : Controller
    {
        private Mobile_appContext db = new Mobile_appContext();

        // GET: /Admin/AdminCustomer/

        public ActionResult index()
        {
            return View("_Login");
        }

        [HttpPost]
        public ActionResult Index()
        {
            if (Request["Email"] == "Admin" && Request["Password"] == "123456" || Request["Email"] == "admin" && Request["Password"] == "123456")
            {
                MvcApplication.IsLoggedInFront = true;
                return RedirectToAction("customerlist", new { Area = "Admin" });
            }
            MvcApplication.showMessage = true;
            MvcApplication.messageTxt = "Your Email or password  is not correct";
            return RedirectToAction("index", new { Area = "Admin" });
        }
        public ActionResult customerlist()
        {
            return View(db.Customers.ToList());
        }

        [HttpPost]
        public ActionResult customerlist(string search)
        {
            search = Request["searchtxt"];
            return View(db.Customers.Where(c => search.Contains(c.UserName)).ToList());
        }

        public ActionResult customerWebsite(int id)
        {
            MvcApplication.CustomerID = id;
            var customerwebsiteids = db.CustomerWebsiteRels.Where(cw => cw.Customer_id == id).Select(w => w.Web_id);
            var customerwebsites = db.Websites.Where(w => customerwebsiteids.Contains(w.web_id)).ToList();
            return View(customerwebsites);
        }


        public ActionResult getAjaxResult(string q)
        {

            string searchResult = string.Empty;

            var customers = (from a in db.Customers
                             where a.UserName.Contains(q)
                             orderby a.UserName
                             select a).Take(10);

            foreach (Customer a in customers)
            {
                searchResult += string.Format("{0}|\r\n", a.UserName);
            }

            return Content(searchResult);
        }



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Search(string searchTerm)
        {
            if (searchTerm == string.Empty)
            {
                return View();
            }
            else
            {
                var customers = from a in db.Customers
                                where a.UserName.Contains(searchTerm)
                                orderby a.UserName
                                select a;

                if (customers.Count() == 0)
                {
                    return View("notfound");
                }

                if (customers.Count() > 1)
                {
                    return View("List", customers);
                }
                else
                {
                    return RedirectToAction("Details",
                        new { id = customers.First().Customer_id });
                }
            }
        }


        //
        // GET: /Admin/AdminCustomer/Details/5


        public ViewResult Details(int id)
        {
            Customer customer = db.Customers.Find(id);
            return View(customer);
        }

        //
        // GET: /Admin/AdminCustomer/Create



        //
        // GET: /Admin/AdminCustomer/Edit/5

        public ActionResult Edit(int id)
        {
            Customer customer = db.Customers.Find(id);
            return View(customer);
        }

        //
        // POST: /Admin/AdminCustomer/Edit/5

        [HttpPost]
        public ActionResult Edit(Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Entry(customer).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("customerlist");
            }
            return View(customer);
        }

        //
        // GET: /Admin/AdminCustomer/Delete/5

        public ActionResult Delete(int id)
        {
            Customer customer = db.Customers.Find(id);
            return View(customer);
        }

        //
        // POST: /Admin/AdminCustomer/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Customer customer = db.Customers.Find(id);
            db.Customers.Remove(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }



        public ActionResult EditWebsite(int? id)
        {
            if (id != null)
            {
                //if (MvcApplication.IsUpdateMode == true)
                //{
                MvcApplication.IsUpdateMode = true;

                MvcApplication._MainCustomer.Website = db.Websites.Where(w => w.web_id == id).FirstOrDefault();
                var ThemeID = db.WebthemeRels.Where(w => w.Web_id == MvcApplication._MainCustomer.Website.web_id).Select(t => t.Theme_id).FirstOrDefault();
                MvcApplication._MainCustomer.MyTheme = db.ThemeDetails.Where(t => t.theme_id == ThemeID).FirstOrDefault();
                MvcApplication._MainCustomer.ContentPages = db.Pages.Where(p => db.ThemePageRELs.Where(c => c.Theme_id == MvcApplication._MainCustomer.MyTheme.theme_id).Select(x => x.Page_id).Contains(p.page_id)).ToList();
                if (MvcApplication._MainCustomer.Website.IsContactusPage == true && MobileWebsiteGenerator.MvcApplication._MainCustomer.ContentPages.Count() != 0)
                    MvcApplication.pageId = MobileWebsiteGenerator.MvcApplication._MainCustomer.ContentPages.Where(p => p.title == "ContactUs").FirstOrDefault().page_id;
                MvcApplication._MainCustomer.PictureGallery = db.pictureGalleries.Where(p => db.ThemePictureRELs.Where(c => c.Theme_id == MvcApplication._MainCustomer.MyTheme.theme_id).Select(x => x.Picture_id).Contains(p.picture_id)).ToList();
                //}
                return View(MvcApplication._MainCustomer);
            }

            return View(MvcApplication._MainCustomer);
        }




        [HttpPost]
        public ActionResult EditWebsite()
        {


            char[] obj = new char[] { ',' };
            if (MvcApplication.IsUpdateMode == false || MvcApplication.IscreateNew == true)
            {
                //Create Customer and if already exist then create new website.

                //Write code for update all data 

                //add Website     

                var website = new Website();
                //var pictureFlag = Request["Website.IsPictureGallery"].Split(obj);
                //if (pictureFlag.Count() == 1)
                website.IsPictureGallery = Convert.ToBoolean(Request["pictureTemp"]);
                //else
                //    website.IsPictureGallery = Convert.ToBoolean(pictureFlag[1]);
                //  website.IsPictureGallery = Convert.ToBoolean(Request["Website.IsPictureGallery"]);
                var contact = Request["Website.IsContactusPage"].Split(obj);
                if (contact.Count() == 1)
                    website.IsContactusPage = Convert.ToBoolean(Request["Website.IsContactusPage"]);
                else
                    website.IsContactusPage = Convert.ToBoolean(contact[1]);
                website.visitorcount = MvcApplication._MainCustomer.Website.visitorcount;
                website.web_url = Request["Website_web_url"];
                string hashCode = String.Format("{0:X}", website.web_url.GetHashCode());
                website.web_url = "http://mwg.com/" + MvcApplication._MainCustomer.customer.UserName + "/" + website.web_url;
                db.Websites.Add(website);
                db.SaveChanges();
                //Customer Website rel




                //Add Customer





                var custwebsite = new CustomerWebsiteREL();
                custwebsite.Customer_id = Convert.ToInt32(MvcApplication.CustomerID);
                custwebsite.Web_id = website.web_id;
                custwebsite.Customer_Web_id = Convert.ToDecimal((db.CustomerWebsiteRels == null || db.CustomerWebsiteRels.Count() == 0) ? 1 : db.CustomerWebsiteRels.Count() + 1);
                db.CustomerWebsiteRels.Add(custwebsite);
                db.SaveChanges();
                //Add theme
                var myTheme = new ThemeDetail();
                myTheme.Headercolor = MvcApplication._MainCustomer.MyTheme.Headercolor;
                myTheme.HeaderImage = MvcApplication._MainCustomer.MyTheme.HeaderImage;
                myTheme.HeaderText = MvcApplication._MainCustomer.MyTheme.HeaderText;
                myTheme.Image = MvcApplication._MainCustomer.MyTheme.Image;
                myTheme.Swatch = MvcApplication._MainCustomer.MyTheme.Swatch;
                myTheme.HHeaderText = MvcApplication._MainCustomer.MyTheme.HHeaderText;
                myTheme.HFootertext = MvcApplication._MainCustomer.MyTheme.HFootertext;

                myTheme.Theme_type = MvcApplication._MainCustomer.MyTheme.Theme_type;
                myTheme.backgroundColor = MvcApplication._MainCustomer.MyTheme.backgroundColor;
                myTheme.backgroundImage = MvcApplication._MainCustomer.MyTheme.backgroundImage;
                db.ThemeDetails.Add(myTheme);
                db.SaveChanges();


                //Theme web rel

                WebthemeRel webthemerel = new WebthemeRel();
                webthemerel.Theme_id = myTheme.theme_id;
                webthemerel.Web_id = website.web_id;
                webthemerel.Web_theme_id = Convert.ToDecimal((db.WebthemeRels == null || db.WebthemeRels.Count() == 0) ? 1 : db.WebthemeRels.Select(wt => wt.Web_theme_id).Max() + 1);
                db.WebthemeRels.Add(webthemerel);






                //Add Picture Gallery
                if (MvcApplication._MainCustomer.Website.IsPictureGallery == true)
                {

                    MvcApplication._MainCustomer.PictureGallery.ForEach(p =>
                    {
                        //Add Picture
                        var piture = new pictureGallery();
                        piture.ImagePath = p.ImagePath;
                        piture.Size = p.Size;
                        db.pictureGalleries.Add(piture);
                        db.SaveChanges();

                        //Add pictureRelWith Theme
                        ThemePictureREL thempic = new ThemePictureREL();
                        thempic.Theme_id = myTheme.theme_id;
                        thempic.Picture_id = piture.picture_id;
                        thempic.Theme_picture_id = Convert.ToDecimal((db.ThemePictureRELs == null || db.ThemePictureRELs.Count() == 0) ? 1 : db.ThemePictureRELs.Select(tp => tp.Theme_picture_id).Max() + 1);
                        db.ThemePictureRELs.Add(thempic);
                        db.SaveChanges();
                    });
                }


                //Add Pages

                MvcApplication._MainCustomer.ContentPages.ForEach(p =>
                {
                    //Add Picture
                    var page = new Page();
                    page.EContent = p.EContent;
                    page.title = p.title;
                    page.HContent = p.HContent;
                    page.HTitle = p.HTitle;
                    db.Pages.Add(page);
                    db.SaveChanges();

                    //Add pictureRelWith Theme
                    ThemePageREL thempic = new ThemePageREL();
                    thempic.Theme_id = myTheme.theme_id;
                    thempic.Page_id = page.page_id;
                    thempic.Theme_Page_id = Convert.ToDecimal((db.ThemePageRELs == null || db.ThemePageRELs.Count() == 0) ? 1 : db.ThemePageRELs.Select(tp => tp.Theme_Page_id).Max() + 1);

                    db.ThemePageRELs.Add(thempic);
                    db.SaveChanges();
                });

            }
            else
            {

                MvcApplication.IsUpdateMode = false;


                var website = db.Websites.Where(web => web.web_id == MvcApplication._MainCustomer.Website.web_id).FirstOrDefault();

                website.web_url = Request["Website_web_url"];

                website.IsPictureGallery = Convert.ToBoolean(Request["pictureTemp"]);
                //if (pictureFlag.Count() == 1)
                //    website.IsPictureGallery = Convert.ToBoolean(Request["Website.IsPictureGallery"]);
                //else
                //    website.IsPictureGallery = Convert.ToBoolean(pictureFlag[1]);

                var contact = Request["Website.IsContactusPage"].Split(obj);
                if (contact.Count() == 1)
                    website.IsContactusPage = Convert.ToBoolean(Request["Website.IsContactusPage"]);
                else
                    website.IsContactusPage = Convert.ToBoolean(contact[1]);
                db.SaveChanges();



                int themeid = db.WebthemeRels.Where(w => w.Web_id == website.web_id).Select(p => p.Theme_id).FirstOrDefault();
                var theme = db.ThemeDetails.Where(t => t.theme_id == themeid).FirstOrDefault();
                theme.Swatch = MvcApplication._MainCustomer.MyTheme.Swatch;
                theme.backgroundColor = MvcApplication._MainCustomer.MyTheme.backgroundColor;
                theme.backgroundImage = MvcApplication._MainCustomer.MyTheme.backgroundImage;
                theme.Footertext = MvcApplication._MainCustomer.MyTheme.Footertext;
                theme.Headercolor = MvcApplication._MainCustomer.MyTheme.Headercolor;
                theme.HeaderText = MvcApplication._MainCustomer.MyTheme.HeaderText;
                theme.HHeaderText = MvcApplication._MainCustomer.MyTheme.HHeaderText;
                theme.HFootertext = MvcApplication._MainCustomer.MyTheme.HFootertext;
                theme.Image = MvcApplication._MainCustomer.MyTheme.Image;
                theme.Swatch = MvcApplication._MainCustomer.MyTheme.Swatch;
                theme.Theme_type = MvcApplication._MainCustomer.MyTheme.Theme_type;
                db.SaveChanges();

                var pages = db.Pages.Where(page => db.ThemePageRELs.Where(p => p.Theme_id == themeid).Select(p => p.Page_id).Contains(page.page_id));

                if (pages != null)
                {

                    pages.ToList().ForEach(p =>
                    {
                        db.ThemePageRELs.Remove(db.ThemePageRELs.Where(tp => tp.Page_id == p.page_id).FirstOrDefault());
                        db.Pages.Remove(p);
                        db.SaveChanges();
                    });

                    MvcApplication._MainCustomer.ContentPages.ForEach(p =>
                    {
                        //Add Picture
                        var page = new Page();
                        page.EContent = p.EContent;
                        page.title = p.title;
                        page.HContent = p.HContent;
                        page.HTitle = p.HTitle;
                        db.Pages.Add(page);
                        db.SaveChanges();

                        //Add pictureRelWith Theme
                        ThemePageREL thempic = new ThemePageREL();
                        thempic.Theme_id = themeid;
                        thempic.Page_id = page.page_id;
                        thempic.Theme_Page_id = Convert.ToDecimal((db.ThemePageRELs == null || db.ThemePageRELs.Count() == 0) ? 1 : db.ThemePageRELs.Select(tpr => tpr.Theme_Page_id).Max() + 1);

                        db.ThemePageRELs.Add(thempic);
                        db.SaveChanges();
                    });

                }



                var pictures = db.pictureGalleries.Where(page => db.ThemePictureRELs.Where(p => p.Theme_id == themeid).Select(p => p.Picture_id).Contains(page.picture_id));

                if (pictures != null)
                {
                    pictures.ToList().ForEach(p =>
                    {
                        db.ThemePictureRELs.Remove(db.ThemePictureRELs.Where(tp => tp.Picture_id == p.picture_id).FirstOrDefault());
                        db.pictureGalleries.Remove(p);
                        db.SaveChanges();
                    });
                    if (website.IsPictureGallery == true)
                    {
                        MvcApplication._MainCustomer.PictureGallery.ForEach(p =>
                        {
                            //Add Picture
                            var piture = new pictureGallery();
                            piture.ImagePath = p.ImagePath;
                            piture.Size = p.Size;
                            db.pictureGalleries.Add(piture);
                            db.SaveChanges();

                            //Add pictureRelWith Theme
                            ThemePictureREL thempic = new ThemePictureREL();
                            thempic.Theme_id = themeid;
                            thempic.Picture_id = piture.picture_id;
                            thempic.Theme_picture_id = Convert.ToDecimal((db.ThemePictureRELs == null || db.ThemePictureRELs.Count() == 0) ? 1 : db.ThemePictureRELs.Select(tpi => tpi.Theme_picture_id).Max() + 1);
                            db.ThemePictureRELs.Add(thempic);
                            db.SaveChanges();
                        });


                    }
                }






            }






            return RedirectToActionPermanent("LastStep");
        }




        public ActionResult MetaTag()
        {
            return View(MvcApplication._MainCustomer);
        }

        [HttpPost]
        public ActionResult MetaTag(MainViewModel MetaTags)
        {

            if (ModelState.IsValid)
            {


                var metatags = new Metatag();
                metatags.MetaID = Convert.ToInt32(Request["MetaID"]);
                metatags.KeyWords = Request["KeyWords"];
                metatags.Description = Request["Description"];
                db.Metatags.Add(metatags);
                db.SaveChanges();


                var webmetarel = new WebMetaREL();
                webmetarel.Meta_ID = metatags.MetaID;
                webmetarel.Web_id = MvcApplication._MainCustomer.Website.web_id;
                webmetarel.Web_Meta_id = Convert.ToDecimal((db.WebMetaRELs == null || db.WebMetaRELs.Count() == 0) ? 1 : db.WebMetaRELs.Count() + 1);
                db.WebMetaRELs.Add(webmetarel);
                db.SaveChanges();
                return RedirectToAction("EditWebsite", new { Area = "Admin" });



            }
            return View(MvcApplication._MainCustomer);

        }


        public ActionResult LastStep()
        {
            MvcApplication._MainCustomer = new MobileWebsiteGenerator.Models.MainViewModel();
            MvcApplication._MainCustomer.customer = new MobileWebsiteGenerator.Entities.Customer();
            MvcApplication._MainCustomer.ContentPages = new List<MobileWebsiteGenerator.Entities.Page>();
            MvcApplication._MainCustomer.MyTheme = new MobileWebsiteGenerator.Entities.ThemeDetail();
            MvcApplication._MainCustomer.PictureGallery = new List<MobileWebsiteGenerator.Entities.pictureGallery>();
            MvcApplication._MainCustomer.Website = new MobileWebsiteGenerator.Entities.Website();
            MvcApplication.IscreateNew = false;
            return View();
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}